from django.shortcuts import render, redirect
from django.http import HttpResponse
from ..models import Department, UserInfo, PrettyNum, Admin
from django import forms
from django.forms import Form, ModelForm
from django.utils.safestring import mark_safe
from ..utils.pagination import Pagination
from ..utils.bootstrap import BootStrapModelForm
from ..utils.form import UserModelForm, PrettynumModelForm, PrettynumEditModelForm, AdminModelForm, AdminEditModelForm, AdminResetModelForm
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


def admin_list(request):
    # 验证用户是否已经登录
    info = request.session['info']
    if not info:
        return redirect('/login/')

    # 搜素
    data_dict = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dict['username__contains'] = search_data
    data_list = Admin.objects.filter(**data_dict)
    page_object = Pagination(request, data_list)
    return render(request, 'admin_list.html',
                  {'data_list': page_object.page_queryset, 'page_string': page_object.html()})

def admin_add(request):
    title = '管理员'
    if request.method == 'GET':
        form = AdminModelForm()
        return render(request, 'change.html', {'form': form ,'title': title})
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'admin_add.html', {'form': form, 'title': title})

def admin_edit(request, nid):
    row_obj = Admin.objects.filter(id=nid).first()
    if not row_obj:
        return render(request, 'error.html', {'msg': '数据不存在'})
    title = '编辑管理员'
    if request.method == 'GET':
        form = AdminEditModelForm(instance=row_obj)
        return render(request, 'change.html', {'title': title, 'form': form})
    form = AdminEditModelForm(data=request.POST, instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'title': title, 'form': form})

def admin_delete(request, nid):
    Admin.objects.filter(id=nid).delete()
    return redirect('/admin/list/')

def admin_reset(request, nid):
    title = '重置密码'
    row_obj = Admin.objects.filter(id=nid).first()
    if not row_obj:
        return render(request, 'error.html', {'msg': '数据不存在'})
    if request.method == 'GET':
        form = AdminResetModelForm(instance=row_obj)
        return render(request, 'change.html', {'title': title, 'form': form})
    form = AdminResetModelForm(data=request.POST, instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'title': title, 'form': form})